import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Modal,
  Form,
  Select,
  message,
  Tag,
  Tooltip,
  Progress,
  Rate,
  Upload,
  Typography,
  Row,
  Col,
  Statistic,
  Divider,
  List,
  Avatar,
  Badge,
  Timeline,
  Tabs,
  Alert,
  Steps,
  Popconfirm,
} from "antd";
import {
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  DownloadOutlined,
  UploadOutlined,
  FileTextOutlined,
  ClockCircleOutlined,
  UserOutlined,
  StarOutlined,
  MessageOutlined,
  BookOutlined,
  EditOutlined,
  LikeOutlined,
  DislikeOutlined,
  RobotOutlined,
  TeamOutlined,
  AuditOutlined,
  RollbackOutlined,
  SendOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  SyncOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons";
import type { UploadFile } from "antd/es/upload/interface";
import { useUser } from "../../../contexts/UserContext";

const { Search } = Input;
const { TextArea } = Input;
const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;

interface HomeworkSubmission {
  id: string;
  studentId: string;
  studentName: string;
  homeworkId: string;
  homeworkName: string;
  courseName: string;
  className: string; // 新增班级字段
  submitTime: string;
  status: "pending" | "ai_graded" | "teacher_reviewed" | "published" | "rejected" | "late" | "resubmitted";
  score?: number;
  totalScore: number;
  files: UploadFile[];
  comments?: string;
  gradedBy?: string;
  gradedTime?: string;
  quality?: number; // 作业质量评分 1-5
  effort?: number; // 努力程度评分 1-5
  creativity?: number; // 创新性评分 1-5
  feedback?: string; // 详细反馈
  resubmissionCount?: number; // 重交次数
  aiScore?: number; // AI评分
  aiComments?: string; // AI评语
  aiQuality?: number; // AI质量评分
  aiEffort?: number; // AI努力程度评分
  aiCreativity?: number; // AI创新性评分
  aiFeedback?: string; // AI详细反馈
  aiGradingDetails?: string; // AI批阅详情
  teacherScore?: number; // 教师评分
  teacherComments?: string; // 教师评语
  teacherQuality?: number; // 教师质量评分
  teacherEffort?: number; // 教师努力程度评分
  teacherCreativity?: number; // 教师创新性评分
  teacherFeedback?: string; // 教师详细反馈
  reviewStatus?: "pending" | "approved" | "rejected"; // 审核状态
  reviewComments?: string; // 审核评语
}

interface HomeworkGradingModalProps {
  visible: boolean;
  submission: HomeworkSubmission | null;
  onOk: (score: number, comments: string, quality: number, effort: number, creativity: number, feedback: string, reviewStatus: string, reviewComments: string) => void;
  onCancel: () => void;
  loading: boolean;
}

const HomeworkGradingModal: React.FC<HomeworkGradingModalProps> = ({
  visible,
  submission,
  onOk,
  onCancel,
  loading,
}) => {
  const [form] = Form.useForm();
  const [score, setScore] = useState<number>(0);
  const [comments, setComments] = useState<string>("");
  const [quality, setQuality] = useState<number>(3);
  const [effort, setEffort] = useState<number>(3);
  const [creativity, setCreativity] = useState<number>(3);
  const [feedback, setFeedback] = useState<string>("");
  const [reviewStatus, setReviewStatus] = useState<string>("approved");
  const [reviewComments, setReviewComments] = useState<string>("");

  useEffect(() => {
    if (submission) {
      setScore(submission.teacherScore || submission.aiScore || 0);
      setComments(submission.teacherComments || submission.aiComments || "");
      setQuality(submission.teacherQuality || submission.aiQuality || 3);
      setEffort(submission.teacherEffort || submission.aiEffort || 3);
      setCreativity(submission.teacherCreativity || submission.aiCreativity || 3);
      setFeedback(submission.teacherFeedback || submission.aiFeedback || "");
      setReviewStatus(submission.reviewStatus || "approved");
      setReviewComments(submission.reviewComments || "");
      form.setFieldsValue({
        score: submission.teacherScore || submission.aiScore || 0,
        comments: submission.teacherComments || submission.aiComments || "",
        quality: submission.teacherQuality || submission.aiQuality || 3,
        effort: submission.teacherEffort || submission.aiEffort || 3,
        creativity: submission.teacherCreativity || submission.aiCreativity || 3,
        feedback: submission.teacherFeedback || submission.aiFeedback || "",
        reviewStatus: submission.reviewStatus || "approved",
        reviewComments: submission.reviewComments || "",
      });
    }
  }, [submission, form]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onOk(values.score, values.comments, values.quality, values.effort, values.creativity, values.feedback, values.reviewStatus, values.reviewComments);
    } catch (error) {
      message.error("请填写完整信息");
    }
  };

  const handleScoreChange = (value: number) => {
    setScore(value);
    form.setFieldsValue({ score: value });
  };

  const getStatusStep = (submission: HomeworkSubmission) => {
    if (submission.status === "pending") return 0;
    if (submission.status === "ai_graded") return 1;
    if (submission.status === "teacher_reviewed") return 2;
    if (submission.status === "published") return 3;
    return 0;
  };

  return (
    <Modal
      title={`作业批改 - ${submission?.studentName} (${submission?.homeworkName})`}
      open={visible}
      onOk={handleOk}
      onCancel={onCancel}
      width={1100}
      confirmLoading={loading}
      destroyOnClose
    >
      <div style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="学生姓名"
              value={submission?.studentName}
              prefix={<UserOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="作业名称"
              value={submission?.homeworkName}
              prefix={<BookOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="班级"
              value={submission?.className}
              prefix={<TeamOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="提交时间"
              value={submission?.submitTime}
              prefix={<ClockCircleOutlined />}
            />
          </Col>
        </Row>
      </div>

      <Divider />

      {/* 处理流程状态 */}
      <div style={{ marginBottom: 16 }}>
        <Title level={5}>处理流程</Title>
        <Steps current={submission ? getStatusStep(submission) : 0} size="small">
          <Steps.Step title="待批改" icon={<ClockCircleOutlined />} />
          <Steps.Step title="AI批改" icon={<RobotOutlined />} />
          <Steps.Step title="教师审核" icon={<AuditOutlined />} />
          <Steps.Step title="发布成绩" icon={<SendOutlined />} />
        </Steps>
      </div>

      <Divider />

      {/* AI批改结果 */}
      {submission?.aiScore !== undefined && (
        <>
          <div style={{ marginBottom: 16 }}>
            <Title level={5}>
              <RobotOutlined style={{ color: "#1890ff" }} /> AI批改结果
            </Title>
            <Row gutter={16} style={{ marginBottom: 8 }}>
              <Col span={6}>
                <Alert
                  message={`总分: ${submission.aiScore}/${submission.totalScore}`}
                  description="AI综合评分"
                  type="info"
                  showIcon
                />
              </Col>
              <Col span={6}>
                <Alert
                  message={`质量: ${submission.aiQuality || 0}/5`}
                  description="代码质量评分"
                  type="success"
                  showIcon
                />
              </Col>
              <Col span={6}>
                <Alert
                  message={`努力: ${submission.aiEffort || 0}/5`}
                  description="努力程度评分"
                  type="warning"
                  showIcon
                />
              </Col>
              <Col span={6}>
                <Alert
                  message={`创新: ${submission.aiCreativity || 0}/5`}
                  description="创新性评分"
                  type="error"
                  showIcon
                />
              </Col>
            </Row>
            <Alert
              message="AI评语"
              description={submission.aiComments}
              type="info"
              showIcon
              style={{ marginBottom: 8 }}
            />
            <Alert
              message="详细反馈"
              description={submission.aiFeedback}
              type="info"
              showIcon
              style={{ marginBottom: 8 }}
            />
            <Alert
              message="批改详情"
              description={submission.aiGradingDetails}
              type="info"
              showIcon
              style={{ marginBottom: 8 }}
            />
          </div>
          <Divider />
        </>
      )}

      <div style={{ marginBottom: 16 }}>
        <Title level={5}>学生提交的文件</Title>
        <List
          itemLayout="horizontal"
          dataSource={submission?.files || []}
          renderItem={(file) => (
            <List.Item
              actions={[
                <Button
                  key="download"
                  type="link"
                  icon={<DownloadOutlined />}
                  onClick={() => window.open(file.url)}
                >
                  下载
                </Button>,
                <Button
                  key="preview"
                  type="link"
                  icon={<EyeOutlined />}
                  onClick={() => window.open(file.url)}
                >
                  预览
                </Button>,
              ]}
            >
              <List.Item.Meta
                avatar={<FileTextOutlined style={{ fontSize: 24 }} />}
                title={file.name}
                description={`大小: ${(file.size || 0) / 1024}KB`}
              />
            </List.Item>
          )}
        />
      </div>

      <Divider />

      <Form form={form} layout="vertical">
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="score"
              label="评分"
              rules={[
                { required: true, message: "请输入分数" },
                { type: "number", min: 0, max: submission?.totalScore || 100, message: "分数超出范围" },
              ]}
            >
              <Input
                type="number"
                placeholder={`0-${submission?.totalScore || 100}`}
                addonAfter={`/ ${submission?.totalScore || 100}`}
                onChange={(e) => handleScoreChange(Number(e.target.value))}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="重交次数">
              <Text type="secondary">
                {submission?.resubmissionCount || 0} 次
              </Text>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="quality"
              label="作业质量"
              rules={[{ required: true, message: "请评分" }]}
            >
              <Rate
                value={quality}
                onChange={setQuality}
                count={5}
                style={{ fontSize: 16 }}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="effort"
              label="努力程度"
              rules={[{ required: true, message: "请评分" }]}
            >
              <Rate
                value={effort}
                onChange={setEffort}
                count={5}
                style={{ fontSize: 16 }}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="creativity"
              label="创新性"
              rules={[{ required: true, message: "请评分" }]}
            >
              <Rate
                value={creativity}
                onChange={setCreativity}
                count={5}
                style={{ fontSize: 16 }}
              />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="comments"
          label="评语"
          rules={[{ required: true, message: "请输入评语" }]}
        >
          <TextArea
            rows={3}
            placeholder="请输入简短的评语..."
            value={comments}
            onChange={(e) => setComments(e.target.value)}
          />
        </Form.Item>

        <Form.Item
          name="feedback"
          label="详细反馈"
          rules={[{ required: true, message: "请输入详细反馈" }]}
        >
          <TextArea
            rows={4}
            placeholder="请输入详细的反馈和建议..."
            value={feedback}
            onChange={(e) => setFeedback(e.target.value)}
          />
        </Form.Item>

        <Form.Item
          name="reviewStatus"
          label="审核结果"
          rules={[{ required: true, message: "请选择审核结果" }]}
        >
          <Select
            value={reviewStatus}
            onChange={setReviewStatus}
            placeholder="请选择审核结果"
          >
            <Select.Option value="approved">
              <CheckCircleOutlined style={{ color: "#52c41a" }} /> 通过
            </Select.Option>
            <Select.Option value="rejected">
              <ExclamationCircleOutlined style={{ color: "#ff4d4f" }} /> 打回重批
            </Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="reviewComments"
          label="审核评语"
          rules={[{ required: true, message: "请输入审核评语" }]}
        >
          <TextArea
            rows={3}
            placeholder="请输入审核评语..."
            value={reviewComments}
            onChange={(e) => setReviewComments(e.target.value)}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

const HomeworkGrading: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [submissions, setSubmissions] = useState<HomeworkSubmission[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentSubmission, setCurrentSubmission] = useState<HomeworkSubmission | null>(null);
  const [searchText, setSearchText] = useState("");
  const [selectedClass, setSelectedClass] = useState<string>("all");
  const [selectedStatus, setSelectedStatus] = useState<string>("all");
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [aiGradingLoading, setAiGradingLoading] = useState(false);
  const [publishLoading, setPublishLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<string>("all");

  // 生成模拟数据
  const generateMockSubmissions = (): HomeworkSubmission[] => {
    const classNames = ["计算机科学1班", "计算机科学2班", "软件工程1班", "软件工程2班", "人工智能1班"];
    const homeworkNames = ["算法设计作业", "数据结构实验", "Web开发项目", "数据库设计", "软件测试报告"];
    const courseNames = ["算法与数据结构", "软件工程", "Web开发技术", "数据库原理", "软件测试"];
    const studentNames = [
      "李明轩", "王雨涵", "张浩然", "刘雅琪", "陈思远", "杨梦瑶", "赵天宇", "孙诗涵", "周博文", "吴欣怡",
      "徐子轩", "朱雨桐", "胡志强", "郭雅婷", "何俊杰", "马晓雯", "韩志豪", "郑雅文", "冯浩然", "曹梦琪",
      "彭志强", "董雅涵", "袁博文", "潘雨桐", "田志豪", "姜雅文", "魏浩然", "蒋梦琪", "韦志强", "傅雅涵",
      "沈博文", "卢雨桐", "姚志豪", "钱雅文", "汪浩然", "田梦琪", "任志强", "武雅涵", "戴博文", "贾雨桐",
      "夏志豪", "钟雅文", "邱浩然", "骆梦琪", "高志强", "蔡雅涵", "樊博文", "胡雨桐", "凌志豪", "霍雅文"
    ];

    return Array.from({ length: 80 }, (_, index) => {
      const statuses: ("pending" | "ai_graded" | "teacher_reviewed" | "published" | "rejected" | "late" | "resubmitted")[] = 
        ["pending", "ai_graded", "teacher_reviewed", "published", "rejected", "late", "resubmitted"];
      const status = statuses[index % statuses.length];
      
      const hasAIGrading = status !== "pending";
      const hasTeacherReview = ["teacher_reviewed", "published"].includes(status);
      
      return {
        id: `homework_${index + 1}`,
        studentId: `s${index + 1}`,
        studentName: studentNames[index % studentNames.length],
        homeworkId: `hw_${Math.floor(index / 16) + 1}`,
        homeworkName: homeworkNames[Math.floor(index / 16)],
        courseName: courseNames[Math.floor(index / 16)],
        className: classNames[index % classNames.length],
        submitTime: `2024-01-${String(20 - Math.floor(index / 4)).padStart(2, '0')} ${String(14 + index % 6).padStart(2, '0')}:${String(20 + index % 40).padStart(2, '0')}:00`,
        status,
        score: hasTeacherReview ? Math.floor(Math.random() * 40) + 60 : undefined,
        totalScore: 100,
        files: [
          {
            uid: `file_${index + 1}`,
            name: `作业提交_${studentNames[index % studentNames.length]}.zip`,
            status: 'done',
            url: '#',
            size: 1024 * 1024,
          }
        ],
        comments: hasTeacherReview ? "作业完成度较高，代码结构清晰。" : undefined,
        gradedBy: hasTeacherReview ? user?.name : undefined,
        gradedTime: hasTeacherReview ? `2024-01-${String(21 - Math.floor(index / 4)).padStart(2, '0')} ${String(10 + index % 10).padStart(2, '0')}:${String(30 + index % 30).padStart(2, '0')}:00` : undefined,
        quality: hasTeacherReview ? Math.floor(Math.random() * 3) + 3 : undefined,
        effort: hasTeacherReview ? Math.floor(Math.random() * 3) + 3 : undefined,
        creativity: hasTeacherReview ? Math.floor(Math.random() * 3) + 3 : undefined,
        feedback: hasTeacherReview ? "整体表现良好，建议在创新性方面有所提升。" : undefined,
        resubmissionCount: Math.floor(Math.random() * 3),
        aiScore: hasAIGrading ? Math.floor(Math.random() * 40) + 60 : undefined,
        aiComments: hasAIGrading ? "AI自动评分完成，建议教师进一步审核。" : undefined,
        aiQuality: hasAIGrading ? Math.floor(Math.random() * 3) + 3 : undefined,
        aiEffort: hasAIGrading ? Math.floor(Math.random() * 3) + 3 : undefined,
        aiCreativity: hasAIGrading ? Math.floor(Math.random() * 3) + 3 : undefined,
        aiFeedback: hasAIGrading ? "AI分析：作业质量良好，代码规范，建议教师审核。" : undefined,
        teacherScore: hasTeacherReview ? Math.floor(Math.random() * 40) + 60 : undefined,
        teacherComments: hasTeacherReview ? "经过教师审核，评分合理。" : undefined,
        teacherQuality: hasTeacherReview ? Math.floor(Math.random() * 3) + 3 : undefined,
        teacherEffort: hasTeacherReview ? Math.floor(Math.random() * 3) + 3 : undefined,
        teacherCreativity: hasTeacherReview ? Math.floor(Math.random() * 3) + 3 : undefined,
        teacherFeedback: hasTeacherReview ? "教师反馈：整体表现良好，建议在创新性方面有所提升。" : undefined,
        reviewStatus: hasTeacherReview ? (status === "published" ? "approved" : "rejected") : undefined,
        reviewComments: hasTeacherReview ? (status === "published" ? "审核通过，可以发布成绩。" : "需要重新批改。") : undefined,
      };
    });
  };

  const fetchSubmissions = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      const mockData = generateMockSubmissions();
      setSubmissions(mockData);
    } catch (error) {
      message.error("获取作业提交数据失败");
    } finally {
      setLoading(false);
    }
  };

  const gradeHomework = async (
    submissionId: string, 
    score: number, 
    comments: string, 
    quality: number, 
    effort: number, 
    creativity: number, 
    feedback: string,
    reviewStatus: string,
    reviewComments: string
  ) => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setSubmissions(prev => prev.map(submission => {
        if (submission.id === submissionId) {
          return {
            ...submission,
            teacherScore: score,
            teacherComments: comments,
            teacherQuality: quality,
            teacherEffort: effort,
            teacherCreativity: creativity,
            teacherFeedback: feedback,
            reviewStatus: reviewStatus as "approved" | "rejected",
            reviewComments: reviewComments,
            status: reviewStatus === "approved" ? "teacher_reviewed" : "rejected",
            gradedBy: user?.name,
            gradedTime: new Date().toLocaleString(),
          };
        }
        return submission;
      }));

      message.success("批改完成");
      setModalVisible(false);
    } catch (error) {
      message.error("批改失败");
    } finally {
      setLoading(false);
    }
  };

  const showGradingModal = (submission: HomeworkSubmission) => {
    setCurrentSubmission(submission);
    setModalVisible(true);
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  const handleAIBatchGrading = async () => {
    if (selectedRows.length === 0) {
      message.warning("请选择要批量AI批改的作业");
      return;
    }

    setAiGradingLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      setSubmissions(prev => prev.map(submission => {
        if (selectedRows.includes(submission.id) && submission.status === "pending") {
          // 模拟不同的AI批改结果
          const gradingResults = [
            {
              score: 85,
              quality: 4,
              effort: 4,
              creativity: 3,
              comments: "作业完成度很高，代码结构清晰，注释详细。建议在算法优化方面可以更有创新性。",
              feedback: "代码质量优秀，逻辑清晰，但创新性有待提升。建议尝试不同的解题思路。",
              details: "代码规范性：优秀，算法实现：良好，注释完整性：优秀，创新性：一般。"
            },
            {
              score: 92,
              quality: 5,
              effort: 5,
              creativity: 4,
              comments: "整体表现卓越，代码质量高，算法优化到位，体现了良好的编程思维。",
              feedback: "代码结构清晰，算法效率高，创新性较强。建议继续保持这种学习态度。",
              details: "代码规范性：优秀，算法实现：优秀，注释完整性：优秀，创新性：良好。"
            },
            {
              score: 78,
              quality: 3,
              effort: 4,
              creativity: 3,
              comments: "作业基本完成，但代码结构可以更清晰，建议加强代码规范性的训练。",
              feedback: "完成度较高，但代码质量有待提升。建议多参考优秀代码示例。",
              details: "代码规范性：一般，算法实现：良好，注释完整性：良好，创新性：一般。"
            },
            {
              score: 88,
              quality: 4,
              effort: 5,
              creativity: 4,
              comments: "作业完成度很高，体现了良好的学习态度。代码质量优秀，创新性较强。",
              feedback: "代码结构合理，算法实现正确，创新性表现良好。建议继续保持。",
              details: "代码规范性：良好，算法实现：优秀，注释完整性：优秀，创新性：良好。"
            },
            {
              score: 95,
              quality: 5,
              effort: 5,
              creativity: 5,
              comments: "作业质量极高，代码优雅，算法创新，体现了扎实的编程功底和创新能力。",
              feedback: "代码质量卓越，算法创新性强，整体表现优秀。建议分享给其他同学学习。",
              details: "代码规范性：优秀，算法实现：优秀，注释完整性：优秀，创新性：优秀。"
            }
          ];
          
          const result = gradingResults[Math.floor(Math.random() * gradingResults.length)];
          
          return {
                ...submission,
            status: "ai_graded",
            aiScore: result.score,
            aiComments: result.comments,
            aiQuality: result.quality,
            aiEffort: result.effort,
            aiCreativity: result.creativity,
            aiFeedback: result.feedback,
            aiGradingDetails: result.details,
            gradedBy: "AI助手",
            gradedTime: new Date().toLocaleString(),
          };
        }
        return submission;
      }));

      message.success(`成功完成${selectedRows.length}个作业的AI批改`);
      setSelectedRows([]);
    } catch (error) {
      message.error("AI批量批改失败");
    } finally {
      setAiGradingLoading(false);
    }
  };

  const handlePublishGrades = async () => {
    const reviewedSubmissions = submissions.filter(s => s.status === "teacher_reviewed");
    if (reviewedSubmissions.length === 0) {
      message.warning("没有可发布的成绩");
      return;
    }

    setPublishLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));

      setSubmissions(prev => prev.map(submission => {
        if (submission.status === "teacher_reviewed") {
          return {
                ...submission,
            status: "published",
            score: submission.teacherScore,
            comments: submission.teacherComments,
            quality: submission.teacherQuality,
            effort: submission.teacherEffort,
            creativity: submission.teacherCreativity,
            feedback: submission.teacherFeedback,
          };
        }
        return submission;
      }));

      message.success(`成功发布${reviewedSubmissions.length}个成绩`);
    } catch (error) {
      message.error("发布成绩失败");
    } finally {
      setPublishLoading(false);
    }
  };

  const handleRejectAndRegrade = async (submissionId: string) => {
    setSubmissions(prev => prev.map(submission => {
      if (submission.id === submissionId) {
        return {
          ...submission,
          status: "pending",
          aiScore: undefined,
          aiComments: undefined,
          aiQuality: undefined,
          aiEffort: undefined,
          aiCreativity: undefined,
          aiFeedback: undefined,
          aiGradingDetails: undefined,
          teacherScore: undefined,
          teacherComments: undefined,
          teacherQuality: undefined,
          teacherEffort: undefined,
          teacherCreativity: undefined,
          teacherFeedback: undefined,
          reviewStatus: undefined,
          reviewComments: undefined,
          gradedBy: undefined,
          gradedTime: undefined,
          resubmissionCount: (submission.resubmissionCount || 0) + 1,
        };
      }
      return submission;
    }));
    message.success("已打回重批");
  };

  useEffect(() => {
    fetchSubmissions();
  }, []);

  // 过滤数据
  const filteredSubmissions = submissions.filter(submission => {
    const matchesSearch = !searchText || 
      submission.studentName.includes(searchText) || 
      submission.homeworkName.includes(searchText) ||
      submission.courseName.includes(searchText) ||
      submission.className.includes(searchText);
    
    const matchesClass = selectedClass === "all" || submission.className === selectedClass;
    const matchesStatus = selectedStatus === "all" || submission.status === selectedStatus;
    
    return matchesSearch && matchesClass && matchesStatus;
  });

  // 统计数据
  const stats = {
    total: submissions.length,
    pending: submissions.filter(s => s.status === "pending").length,
    aiGraded: submissions.filter(s => s.status === "ai_graded").length,
    teacherReviewed: submissions.filter(s => s.status === "teacher_reviewed").length,
    published: submissions.filter(s => s.status === "published").length,
    rejected: submissions.filter(s => s.status === "rejected").length,
    resubmitted: submissions.filter(s => s.status === "resubmitted").length,
  };

  const classOptions = Array.from(new Set(submissions.map(s => s.className))).map(className => ({
    label: className,
    value: className,
  }));

  const statusOptions = [
    { label: "全部", value: "all" },
    { label: "待批改", value: "pending" },
    { label: "AI已批改", value: "ai_graded" },
    { label: "教师已审核", value: "teacher_reviewed" },
    { label: "已发布", value: "published" },
    { label: "已打回", value: "rejected" },
    { label: "重新提交", value: "resubmitted" },
  ];

  const columns = [
    {
      title: "学生姓名",
      dataIndex: "studentName",
      key: "studentName",
      width: 100,
    },
    {
      title: "作业名称",
      dataIndex: "homeworkName",
      key: "homeworkName",
      width: 150,
    },
    {
      title: "课程名称",
      dataIndex: "courseName",
      key: "courseName",
      width: 120,
    },
    {
      title: "班级",
      dataIndex: "className",
      key: "className",
      width: 120,
    },
    {
      title: "提交时间",
      dataIndex: "submitTime",
      key: "submitTime",
      width: 150,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 120,
      render: (status: string) => {
        const statusConfig = {
          pending: { color: "orange", text: "待批改", icon: <ClockCircleOutlined /> },
          ai_graded: { color: "blue", text: "AI已批改", icon: <RobotOutlined /> },
          teacher_reviewed: { color: "green", text: "教师已审核", icon: <AuditOutlined /> },
          published: { color: "green", text: "已发布", icon: <CheckCircleOutlined /> },
          rejected: { color: "red", text: "已打回", icon: <RollbackOutlined /> },
          late: { color: "red", text: "逾期提交", icon: <ExclamationCircleOutlined /> },
          resubmitted: { color: "purple", text: "重新提交", icon: <SyncOutlined /> },
        };
        const config = statusConfig[status as keyof typeof statusConfig] || { color: "default", text: status, icon: <QuestionCircleOutlined /> };
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: "AI评分",
      dataIndex: "aiScore",
      key: "aiScore",
      width: 120,
      render: (score: number, record: HomeworkSubmission) => {
        if (record.aiScore !== undefined) {
          return (
            <Space direction="vertical" size="small">
        <Space>
                <Text strong>{score}</Text>
                <Text type="secondary">/ {record.totalScore}</Text>
        </Space>
              <Space size="small">
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  质量:{record.aiQuality || 0}
                </Text>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  努力:{record.aiEffort || 0}
                </Text>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  创新:{record.aiCreativity || 0}
                </Text>
              </Space>
            </Space>
          );
        }
        return <Text type="secondary">-</Text>;
      },
    },
    {
      title: "教师评分",
      dataIndex: "teacherScore",
      key: "teacherScore",
      width: 100,
      render: (score: number, record: HomeworkSubmission) => {
        if (record.teacherScore !== undefined) {
          return (
        <Space>
              <Text strong>{score}</Text>
              <Text type="secondary">/ {record.totalScore}</Text>
        </Space>
          );
        }
        return <Text type="secondary">-</Text>;
      },
    },
    {
      title: "重交次数",
      dataIndex: "resubmissionCount",
      key: "resubmissionCount",
      width: 100,
      render: (count: number) => (
        <Badge count={count} showZero />
      ),
    },
    {
      title: "操作",
      key: "action",
      width: 200,
      render: (_: any, record: HomeworkSubmission) => (
        <Space size="small">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
            onClick={() => showGradingModal(record)}
          >
            查看
          </Button>
          {record.status === "ai_graded" && (
            <Button
              type="link"
              size="small"
              icon={<AuditOutlined />}
              onClick={() => showGradingModal(record)}
            >
              审核
            </Button>
          )}
          {record.status === "teacher_reviewed" && (
            <Popconfirm
              title="确定打回重批吗？"
              onConfirm={() => handleRejectAndRegrade(record.id)}
              okText="确定"
              cancelText="取消"
            >
            <Button
              type="link"
              size="small"
                danger
                icon={<RollbackOutlined />}
              >
                打回重批
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card title="作业批改管理" style={{ marginBottom: 16 }}>
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={4}>
            <Statistic
              title="总提交数"
              value={stats.total}
              prefix={<FileTextOutlined />}
            />
        </Col>
          <Col span={4}>
            <Statistic
              title="待批改"
              value={stats.pending}
              valueStyle={{ color: "#fa8c16" }}
              prefix={<ClockCircleOutlined />}
            />
        </Col>
          <Col span={4}>
            <Statistic
              title="AI已批改"
              value={stats.aiGraded}
              valueStyle={{ color: "#1890ff" }}
              prefix={<RobotOutlined />}
            />
          </Col>
          <Col span={4}>
            <Statistic
              title="教师已审核"
              value={stats.teacherReviewed}
              valueStyle={{ color: "#52c41a" }}
              prefix={<AuditOutlined />}
            />
        </Col>
          <Col span={4}>
            <Statistic
              title="已发布"
              value={stats.published}
              valueStyle={{ color: "#52c41a" }}
              prefix={<CheckCircleOutlined />}
            />
          </Col>
          <Col span={4}>
            <Statistic
              title="重新提交"
              value={stats.resubmitted}
              valueStyle={{ color: "#722ed1" }}
              prefix={<SyncOutlined />}
            />
        </Col>
      </Row>

        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Search
              placeholder="搜索学生姓名、作业名称、课程或班级..."
              onSearch={handleSearch}
              style={{ width: "100%" }}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择班级"
              value={selectedClass}
              onChange={setSelectedClass}
              style={{ width: "100%" }}
              options={[{ label: "全部班级", value: "all" }, ...classOptions]}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择状态"
              value={selectedStatus}
              onChange={setSelectedStatus}
              style={{ width: "100%" }}
              options={statusOptions}
            />
          </Col>
          <Col span={10}>
          <Space>
            <Button
              type="primary"
              icon={<RobotOutlined />}
                loading={aiGradingLoading}
                onClick={handleAIBatchGrading}
                disabled={selectedRows.length === 0}
            >
                AI批量批改 ({selectedRows.length})
            </Button>
              <Button
                type="primary"
                icon={<SendOutlined />}
                loading={publishLoading}
                onClick={handlePublishGrades}
                disabled={stats.teacherReviewed === 0}
              >
                发布成绩 ({stats.teacherReviewed})
                </Button>
              </Space>
          </Col>
        </Row>
      </Card>

      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="全部作业" key="all" />
          <TabPane tab="待批改" key="pending" />
          <TabPane tab="AI已批改" key="ai_graded" />
          <TabPane tab="教师已审核" key="teacher_reviewed" />
          <TabPane tab="已发布" key="published" />
        </Tabs>

        <Table
          columns={columns}
          dataSource={filteredSubmissions.filter(s => 
            activeTab === "all" || s.status === activeTab
          )}
          rowKey="id"
          loading={loading}
          pagination={{
            total: filteredSubmissions.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          rowSelection={{
            selectedRowKeys: selectedRows,
            onChange: (selectedRowKeys) => setSelectedRows(selectedRowKeys as string[]),
            getCheckboxProps: (record) => ({
              disabled: record.status !== "pending",
            }),
          }}
          scroll={{ x: 1400 }}
        />
      </Card>

      <HomeworkGradingModal
        visible={modalVisible}
        submission={currentSubmission}
        onOk={(score, comments, quality, effort, creativity, feedback, reviewStatus, reviewComments) => 
          currentSubmission && gradeHomework(currentSubmission.id, score, comments, quality, effort, creativity, feedback, reviewStatus, reviewComments)
        }
        onCancel={() => setModalVisible(false)}
            loading={loading}
      />
                  </div>
  );
};

export default HomeworkGrading;
